package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WemediaMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class WmUserServiceImpl extends ServiceImpl<WemediaMapper , WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        if(dto.getName() == null || dto.getPassword() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "请输入用户名或密码");
        }
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName , dto.getName());
        List<WmUser> list = list(wrapper);
        if(list != null && list.size() == 1){
            WmUser wmUser = list.get(0);
            String pass = DigestUtils.md5DigestAsHex((dto.getPassword()+wmUser.getSalt()).getBytes());
            if(pass.equals(wmUser.getPassword())){
                Map map = new HashMap();
                map.put("token" , AppJwtUtil.getToken(wmUser.getId().longValue()));
                wmUser.setSalt("");
                wmUser.setPassword("");
                map.put("user" , wmUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "密码错误");
            }

        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "用户名不存在");
    }
}
